package pump

import (
	"apidoc2entity/model"
	"fmt"
	"github.com/360EntSecGroup-Skylar/excelize"
	"path"
	"strconv"
)

type ExcelPump struct {
	Dir       string
	FileName  string
	SheetName string
}

func NewPumpOfExcel() *ExcelPump {
	pump := &ExcelPump{}
	return pump
}

func (pump *ExcelPump) PickerPump() []model.BuilderField {
	f, err := excelize.OpenFile(pump.FileName)
	if err != nil {
		println(err.Error())
		return nil
	}
	res := []model.BuilderField{}
	s := f.GetSheetName(f.GetActiveSheetIndex())
	rows := f.GetRows(s)
	// 分组
	for _, row := range rows {
		l, _ := strconv.Atoi(row[7])
		var isFields bool
		if len(row) > 8 && row[8] == "1" {
			isFields = true
		}
		res = append(res, model.BuilderField{
			PackageCode: row[0],
			StructCode:  row[0],
			StructName:  row[1],
			FieldCode:   row[2],
			FieldAlias:  row[6],
			FieldName:   row[3],
			FieldType:   row[4],
			Fields:      isFields,
			FieldLength: int32(l),
			FieldAnno:   row[5],
		})
	}
	return res
}

// 创建模板文件
func CreateTemple(dir string) {
	f := excelize.NewFile()
	// Create a new sheet.
	index := f.NewSheet("YourPackageName")
	heads := map[string]string{
		"A1": "结构名或类名",
		"B1": "结构中文名或类中文名",
		"C1": "字段",
		"D1": "字段名",
		"E1": "字段类型",
		"F1": "备注",
		"G1": "别称",
		"H1": "字段长度",
		"I1": "是否集合（1=true）"}
	// Set value of a cell.
	for k, v := range heads {
		f.SetCellValue("YourPackageName", k, v)
	}
	// Set active sheet of the workbook.
	f.SetActiveSheet(index)
	// Save xlsx file by the given path.
	if err := f.SaveAs(path.Join(dir, "temple.xlsx")); err != nil {
		fmt.Println(err)
	}
}
